﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using EnglishStudy.Resources;
using System.Windows.Media;
using Windows.Phone.Speech.Synthesis;
using Windows.Foundation;
using System.Diagnostics;
using EnglishStudy.Entity;
using System.Windows.Media.Imaging;
using EnglishStudy.ViewModel;
using System.IO.IsolatedStorage;
namespace EnglishStudy
{
    public partial class MainPage : PhoneApplicationPage
    {
        SpeechSynthesizer synth;
        string ssmlText;
        // Constructor
        string DBConnectionString = "Data Source=isostore:/LessonData.sdf";
        HomePageViewModel viewModel;
        public MainPage()
        {
            InitializeComponent();
            viewModel = new HomePageViewModel(DBConnectionString);
            App.ViewModel.LoadUserData();
            DataContext = viewModel;
            synth = new SpeechSynthesizer();
            // Add the event handler for the speech progress events
            synth.BookmarkReached += synth_BookmarkReached;
            Loaded += MainPage_Loaded;
            listPicker.Loaded += listPicker_Loaded;
            listPicker.SelectionChanged += listPicker_SelectionChanged;
            SayHelloWhenStartApp();
        }




        private void LoadInformationUser()
        {
            try
            {
                if (PhoneApplicationService.Current.State["UserFacebook"] != null)
                {
                    FacebookUser user = PhoneApplicationService.Current.State["UserFacebook"] as FacebookUser;
                    txtName.Text = user.Name;
                    txtCountry.Text = user.Location.Name.ToString();
                    imageUser.Source = new BitmapImage(new Uri(user.Avatar, UriKind.Absolute));
                }
            }
            catch (Exception)
            {


            }

        }


        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            LoadInformationUser();
            viewModel.LoadCollectionsFromDatabase();
        }

        private void synth_BookmarkReached(SpeechSynthesizer sender, SpeechBookmarkReachedEventArgs args)
        {
            //Logs a message with the name of the mark reached
            Debugger.Log(1, "Info", args.Bookmark + " mark reached\n");
        }

        private async void SayHelloWhenStartApp()
        {
            ssmlText = "<speak version=\"1.0\" ";
            ssmlText += "xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-US\">";
            ssmlText += "Hello";
            ssmlText += "</speak>";

            // Speak the SSML document.
            await synth.SpeakSsmlAsync(ssmlText);
        }

        private void ChooseColor_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //TextBlock a = sender as TextBlock;
            //string colorName = a.Text;
            //Colors co = GetColor(colorName);
            //LayoutRoot.Background =new SolidColorBrush( co);
        }

        private void ChooseColor(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            LayoutRoot.Background = btn.Background;
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/View/LessonPage.xaml", UriKind.Relative));
        }
        bool isListPickerLoaded = false;
        void listPicker_Loaded(object sender, RoutedEventArgs e)
        {
            if (isListPickerLoaded == false)
            {
                isListPickerLoaded = true;
                if (App.ViewModel.UserInfo.LanguageCode == null)
                    App.ViewModel.UserInfo.LanguageCode = "0";

                if (!string.IsNullOrEmpty(App.currentCountry) && App.ViewModel.UserInfo.LanguageCode == "0")
                {
                    // Specify the query for all to-do items in the database.
                    var languageCode = from Country item in viewModel.LanguageList
                                       where item.Code.Split('-').Last().ToLower() == App.currentCountry.ToLower()
                                       select item;
                    if (languageCode != null && languageCode.Count() > 0)
                        App.ViewModel.UserInfo.LanguageCode = languageCode.ToArray()[0].Id.ToString();
                }

                int languageCodeID = int.Parse(App.ViewModel.UserInfo.LanguageCode);
                if (languageCodeID > 0)
                    languageCodeID = languageCodeID - 1;
                listPicker.SelectedIndex = languageCodeID;

            }
            else
            {
                App.ViewModel.UserInfo.LanguageCode = listPicker.SelectedIndex.ToString();
                App.ViewModel.CountryInfo = listPicker.SelectedItem as Country;
                App.ViewModel.SaveChangesToDB();
            }

        }
        void listPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            App.ViewModel.CountryInfo = listPicker.SelectedItem as Country;
        }

        private void genderToggle_Checked(object sender, RoutedEventArgs e)
        {
            if (genderToggle.IsChecked == true)
            {
                App.ViewModel.UserInfo.SpeakerGender = true;
                genderToggle.Content = "Male";
                genderToggle.IsChecked = false;
            }
            else
            {
                App.ViewModel.UserInfo.SpeakerGender = false;
                genderToggle.Content = "Female";
                genderToggle.IsChecked = true;
            }
        }

        private void genderToggle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ImageBrush background = new ImageBrush();
            if (App.ViewModel.UserInfo.SpeakerGender == true)
            {
                App.ViewModel.UserInfo.SpeakerGender = false;
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\woman.png", UriKind.Relative));
            }
            else
            {
                App.ViewModel.UserInfo.SpeakerGender = true;
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\male-sign.png", UriKind.Relative));
            }
            genderToggle.Background = background;
            App.ViewModel.SaveChangesToDB();
        }

        private void genderToggle_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.ViewModel.UserInfo.SpeakerGender == true)
            {
                ImageBrush background = new ImageBrush();
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\male-sign.png", UriKind.Relative));
                background.Stretch = Stretch.UniformToFill;
                genderToggle.Background = background;
            }
            else
            {
                ImageBrush background = new ImageBrush();
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\woman.png", UriKind.Relative));
                background.Stretch = Stretch.UniformToFill;
                genderToggle.Background = background;
            }
        }
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        private void CountryToggle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ImageBrush background = new ImageBrush();
            if (isUSVoice == true)
            {
                isUSVoice = false;
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\ukFlag.png", UriKind.Relative));
            }
            else
            {
                isUSVoice = true;
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\usFlag.png", UriKind.Relative));
            }
            settings["isUSVoice"] = isUSVoice;
            CountryToggle.Background = background;
            App.ViewModel.SaveChangesToDB();
        }
        bool isUSVoice = true;
        private void CountryToggle_Loaded(object sender, RoutedEventArgs e)
        {
            if (settings.Contains("isUSVoice"))
            {
                isUSVoice = (bool)settings["isUSVoice"];
            }
            else settings.Add("isUSVoice", isUSVoice);
            ImageBrush background = new ImageBrush();

            if (isUSVoice)
            {
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\usFlag.png", UriKind.Relative));
            }
            else
            {
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"\Images\Icon\ukFlag.png", UriKind.Relative));
            }
            background.Stretch = Stretch.UniformToFill;
            CountryToggle.Background = background;
        }

        private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/View/VocabularyPage.xaml", UriKind.Relative));
        }

    }
}